<template>
  <div v-if="loading">正在加载...</div>
  <el-select
    v-else
    :value="value"
    :major-id="majorId"
    :show-class-name="showClassName"
    placeholder="请选择班级"
    @change="$emit('input', $event)"
  >
    <el-option
      v-for="item in classList"
      :key="item.id"
      :label="item.className"
      :value="item.id"
    />
  </el-select>
</template>

<script>
import { getClassList } from '@/api/admin/class'

export default {
  name: 'ClassSelect',
  props: {
    value: {
      type: Number,
      default: undefined
    },
    majorId: {
      type: Number,
      default: undefined
    },
    showClassName: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      loading: true,
      classList: []
    }
  },
  watch: {
    majorId(val, oldVal) {
      // 重置id时清空当前值不需要发送请求
      if (val === undefined) {
        this.$emit('input', undefined)
        return
      }
      // id变化时清空当前值并重新发送请求
      if (val !== oldVal) {
        this.$emit('input', undefined)
        this.getClassList()
      }
    }
  },
  created() {
    this.showClassName ? this.getClassList() : this.loading = false
  },
  methods: {
    /**
       * 获取班级信息
       */
    async getClassList() {
      this.classList = await getClassList(this.majorId)
      this.loading = false
    }
  }
}
</script>
